<?php

namespace App\Imports;

use App\Models\Building;
use App\Models\StaffPosition;
use App\Models\Department;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Support\Collection;
use Illuminate\Database\Eloquent\Model;
use App\Models\Dorm;
use App\Models\DormType;
use App\Models\Staff;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use Carbon\Carbon;


class NewCompanyStaffImport implements ToCollection
{
  protected $company_id;
  protected $waterFeeTypeId = 5;
  protected $electricFeeTypeId = 5;
  protected $hotWaterFeeTypeId = 1;
  protected $manageFeeTypeId = 14;

  public function __construct($company_id)
  {
    $this->company_id = $company_id;
  }
  /**
   * @param array $collection
   */
  public function collection(Collection $rows)
  {
    $validRows = $rows->splice(2)->filter(
      function ($r) {
        return count($r) > 9;
      }
    );

    $mapRows = $validRows->map(function ($r) {
      $r[0] = trim($r[0]);
      $r[1] = trim($r[1]);
      $r[2] = trim($r[2]);
      $r[3] = trim($r[3]);
      $r[4] = trim($r[4]);
      $r[5] = trim($r[5]);
      $r[6] = trim($r[6]);
      $r[7] = trim($r[7]);
      $infos = explode('#', $r[9]);

      return [
        'name' => $r[1],
        'id_card' => $r[2],
        'card_num' => $r[3],
        'sex' => $r[4] ? ($r[4] == '男' ? 1 : 2) : 0,
        'date_enroll' => $this->convertDate($r[5]),
        'department' => $r[6],
        'position' => $r[7],
        'phone' => $r[8],
        'code' => $r[9],
        'latest_in_date' => $this->convertDate($r[10]),
        'short_name' => $infos[0],
        'floor' => strlen($infos[1]) == 3 ? substr($infos[1], 0, 1) : substr($infos[1], 0, 2),
        'room' => substr($infos[1], -1)
      ];
    });

    //创建部门
    $depts = $mapRows->pluck('department')->filter()->unique();
    $dept_nameids = [];
    foreach ($depts as $dept) {
      $d = Department::updateOrCreate(
        ['name' => $dept],
        ['company_id' => $this->company_id]
      );
      $dept_nameids[$dept] = $d->id;
    }
    //创建岗位
    $pos = $mapRows->pluck('position')->filter()->unique();
    $poIds = [];
    foreach ($pos as $p) {
      $d = StaffPosition::updateOrCreate(
        ['position' => $p],
        ['company_id' => $this->company_id]
      );
      $t = DormType::updateOrCreate([
        'company_id' => $this->company_id,
        'name' => $p
      ], [
        'company_id' => $this->company_id,
        'name' => $p,
        'staff_position_id' => $d->id,
        'water_fee_type_id' => $this->waterFeeTypeId,
        'electric_fee_type_id' => $this->electricFeeTypeId,
        'hot_water_fee_type_id' => $this->hotWaterFeeTypeId,
        'manage_fee_type_id' => $this->manageFeeTypeId,
        'for_gender' => 0,
      ]);
      $poIds[$p] = ['staff_position_id' => $d->id, 'dorm_type_id' => $t->id];
    }

    //创建宿舍
    $dorms = $mapRows->groupBy('short_name');
    foreach ($dorms as $bsn => $buildingDorms) {
      $floors = $buildingDorms->max('floor');
      $rooms = $buildingDorms->max('room');
      $dormList = $buildingDorms->groupBy('code')->map(function ($dorms, $key) {
        return [
          'code' => $key,
          'for_gender' => $dorms->first()['sex'],
          'beds' => $dorms->count(),
          'floor' => $dorms->first()['floor'],
          'position' => $dorms->first()['position'],
        ];
      });
      //1.创建宿舍楼
      $b = Building::updateOrCreate([
        'company_id' => $this->company_id,
        'name' => $bsn . '栋',
      ], [
        'company_id' => $this->company_id,
        'dorm_type_id' => $poIds[$dormList->first()['position']]['dorm_type_id'],
        'name' => $bsn . '栋',
        'short_name' => $bsn,
        'unit_name_type' => 'number',
        'unit_count' => 1,
        'floors' => $floors,
        'rooms_per_floor' => $rooms,
        'beds_per_room' => $dormList->max('beds'),
        'gen_dorm_rule' => '{简称}#{楼层}{流水号:00}'
      ]);

      //2.创建宿舍
      $dormIds = [];
      foreach ($dormList as $dorm) {
        $d = Dorm::updateOrCreate(
          ['company_id' => $this->company_id, 'code' => $dorm['code']],
          [
            'company_id' => $this->company_id,
            'building_id' => $b->id,
            'code' => $dorm['code'],
            'unit_name' => '1',
            'for_gender' => $dorm['for_gender'],
            'dorm_type_id' => $poIds[$dorm['position']]['dorm_type_id'],
            'beds' => $dorm['beds'],
            'floor' => $dorm['floor'],
          ]
        );
        $dormIds[$dorm['code']] = $d->id;
      }

      //3.创建员工
      foreach ($buildingDorms as $row) {
        Staff::updateOrCreate([
          'company_id' => $this->company_id,
          'id_card' => $row['id_card'],
        ], [
          'company_id' => $this->company_id,
          'dorm_id' => $dormIds[$row['code']],
          'staff_position_id' => $poIds[$row['position']]['staff_position_id'],
          'department_id' => $dept_nameids[$row['department']],
          'is_fee_bearer' => 1,
          'name' => $row['name'],
          'card_num' => $row['card_num'],
          'id_card' => $row['id_card'],
          'sex' => $row['sex'],
          'phone' => $row['phone'],
          'latest_in_date' => $row['latest_in_date'],
          'date_enroll' => $row['date_enroll'],
        ]);
      }
    }
  }
  private function convertDate($value)
  {
    // 处理空值
    if (empty($value)) {
      return null;
    }

    // 检查是否为数字（Excel日期格式）
    if (is_numeric($value)) {
      try {
        return Date::excelToDateTimeObject($value);
      } catch (\Exception $e) {
        // 记录日志或返回默认值
        \Log::warning("日期转换失败: {$value}");
        return null;
      }
    }

    // 尝试解析文本日期
    try {
      return Carbon::parse($value);
    } catch (\Exception $e) {
      // 记录不合法的日期格式
      \Log::warning("无效的日期格式: {$value}");
      return null;
    }
  }
}
